package com.framework.common.aspect;

import com.framework.common.config.DynamicDataSource;
import com.framework.common.annotation.DBSwitch;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author zhoubb
 * @version V1.0
 * @Date 2020/4/25 10:54
 * @since JDK 1.8
 */
@Aspect
@Component
public class DataSourceAspect {

    @Pointcut("@annotation(com.framework.common.annotation.DBSwitch)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        DBSwitch dbswitch = method.getAnnotation(DBSwitch.class);
        if(dbswitch == null){
            DynamicDataSource.setDataSource("dbttz");
        }else {
            DynamicDataSource.setDataSource(dbswitch.name());
        }

        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
        }
    }
}
